// import axios, {
//   type AxiosInstance,
//   type AxiosError,
//   type AxiosRequestConfig,
//   AxiosResponse
// } from "axios";
import axios, { type AxiosInstance, AxiosError, type AxiosRequestConfig, type AxiosResponse, AxiosHeaders } from "axios";

import { showFailToast } from "vant";
import { AxiosCanceler } from "./helper/axiosCancel";
import type { ResultData } from "@/api/interface";
import { LOGIN_URL } from "@/config/config";
import { ResultEnum } from "@/enums/httpEnum";
import { checkStatus } from "./helper/checkStatus";
import { useAppStore } from "@/store/modules/app";
import router from "@/router";
import { goFsAuthorize } from "@/utils";
import { storage } from "hdzk-tools";

interface AxiosHeader extends AxiosHeaders {
	Authorization?: string;
}

const axiosCanceler = new AxiosCanceler();
const config = {
	// 默认地址请求地址，可在 .env 开头文件中修改
	baseURL: "",
	// 设置超时时间（10s）
	timeout: ResultEnum.TIMEOUT as number,
	// 跨域时候允许携带凭证
	withCredentials: true
};

const appStore = useAppStore();

class RequestHttp {
	service: AxiosInstance;
	public constructor(config: AxiosRequestConfig) {
		// 实例化axios
		this.service = axios.create(config);

		/**
		 * @description 请求拦截器
		 * 客户端发送请求 -> [请求拦截器] -> 服务器
		 * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
		 */
		this.service.interceptors.request.use(
			(config: AxiosRequestConfig) => {
				if (config.headers?.type !== "upload") {
					const field = config.method === "get" ? "params" : "data";
					config[field] = {
						...config[field],
						createUser: appStore.getUserId(),
						createUserName: appStore.getUserName()
					};
				}

				// * 将当前请求添加到 pending 中
				axiosCanceler.addPending(config);
				// * 如果当前请求不需要显示 loading,在 api 服务中通过指定的第三个参数: { headers: { noLoading: true } }来控制不显示loading，参见loginApi
				// globalStore.setGlobalLoading(showLoading);
				const token = storage.getToken();
				const Authorization = `Bearer ${token}`;
				return {
					...config,
					headers: { ...config.headers, Authorization } as AxiosHeader
				};
			},
			(error: AxiosError) => {
				return Promise.reject(error);
			}
		);

		/**
		 * @description 响应拦截器
		 *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
		 */
		this.service.interceptors.response.use(
			(response: AxiosResponse) => {
				const { data, config } = response;
				// const globalStore = useGlobalStore();
				// * 在请求结束后，移除本次请求，并关闭请求 loading
				axiosCanceler.removePending(config);
				// globalStore.setGlobalLoading(false);
				// tryHideFullScreenLoading();
				// * 登陆失效（code == 599）
				if (data.code == ResultEnum.OVERDUE) {
					showFailToast(data.msg);
					// globalStore.setToken("");
					router.replace(LOGIN_URL);
					return Promise.reject(data);
				}
				// * 全局错误信息拦截（防止下载文件得时候返回数据流，没有code，直接报错）
				if (data.code && data.code !== ResultEnum.SUCCESS && data.code !== 1000) {
					showFailToast(data.msg || data.message || "请求失败");
					return Promise.reject(data);
				}
				// * 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
				return data;
			},
			async (error: AxiosError) => {
				const { response } = error;
				// tryHideFullScreenLoading();
				// globalStore.setGlobalLoading(false);
				// 请求超时单独判断，因为请求超时没有 response
				if (error.message.indexOf("timeout") !== -1) showFailToast("请求超时！请您稍后重试");
				// 根据响应的错误状态码，做不同的处理
				if (response) checkStatus(response.status);
				if (response?.status === 401) {
					storage.removeToken();
					goFsAuthorize();
				}
				// 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
				if (!window.navigator.onLine) router.replace("/500");
				return Promise.reject(error);
			}
		);
	}

	// * 常用请求方法封装
	get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.get(url, { params, ..._object }); // axios 将参数拼在url中
	}
	post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.post(url, params, _object);
	}
	put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.put(url, params, _object);
	}
	delete<T>(url: string, params?: any): Promise<ResultData<T>> {
		return this.service.delete(url, { data: { ...params } }); //axios 将参数放在表体中
	}
	upload<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.post(url, params, {
			headers: {
				type: "upload"
			},
			..._object
		});
	}
}

export default new RequestHttp(config);
